import bcrypt
import json
from typing import Dict, Optional
from pathlib import Path


class UserManager:
    # 用户数据管理

    def __init__(self, db_path: str = "users.json"):
        self.db_path = Path(db_path)
        self._init_db()

    def _init_db(self):
        # 初始化数据库文件
        if not self.db_path.exists():
            with open(self.db_path, 'w') as f:
                json.dump({}, f)

    def register(self, username: str, password: str) -> bool:
        # 注册新用户
        with open(self.db_path, 'r') as f:
            users = json.load(f)

        if username in users:
            return False

        hashed = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
        users[username] = hashed.decode('utf-8')

        with open(self.db_path, 'w') as f:
            json.dump(users, f)
        return True

    def authenticate(self, username: str, password: str) -> bool:
        # 验证用户登录
        with open(self.db_path, 'r') as f:
            users = json.load(f)

        if username not in users:
            return False

        return bcrypt.checkpw(
            password.encode('utf-8'),
            users[username].encode('utf-8')
        )

    def change_password(self, username: str, new_password: str) -> bool:
        # 修改用户密码
        with open(self.db_path, 'r') as f:
            users = json.load(f)

        if username not in users:
            return False

        hashed = bcrypt.hashpw(new_password.encode('utf-8'), bcrypt.gensalt())
        users[username] = hashed.decode('utf-8')

        with open(self.db_path, 'w') as f:
            json.dump(users, f)
        return True